package fr.esiea.es_inf5042.persistance.dao.SQLiteDAO;

import java.util.ArrayList;
import java.util.List;

import android.content.ContentValues;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;

import fr.esiea.es_inf5042.business.User;
import fr.esiea.es_inf5042.persistance.dao.DAO;

public class SQLiteUserDAO extends DAO<User> {

	private SQLiteDatabase database;
		
	private final String COL_NAME = "name";
	
	public SQLiteUserDAO(SQLiteDatabase database) {
		
		this.database = database;
	}

	@Override
	public List<User> getAll(String whereClauses) {
			
		List<User> resultList = null;
		User u = null;
		Cursor cursor = null;
		String sql = null;				
	
		resultList = new ArrayList<User>();
		
		//KSE - Get all users from database.
		sql = "SELECT * FROM " + TABLE_COMMENTS;
		if(whereClauses != null) sql = sql + " WHERE " + whereClauses;
		
		cursor = database.rawQuery(sql, null);
		
		if(cursor.moveToFirst())
		{
			do
			{
				u = new User(
								cursor.getInt(0),
								cursor.getString(1)
							);
				
				resultList.add(u);
			}
			while(cursor.moveToNext());
		}
		
		return resultList;
	}

	@Override
	public User find(int id) {

		User u = null;
		Cursor cursor = null;
		String sql = null;	
		
		//KSE - Find user by id attribute.
		sql  = "SELECT * FROM " + TABLE_USERS + " WHERE id = " + String.valueOf(id);		
		cursor = database.rawQuery(sql, null);
		
		if(cursor.moveToFirst())
			u = new User(cursor.getInt(0), cursor.getString(1));
				
		return u;
	}

	@Override
	public User create(User obj) {
				
		Cursor cursor = null;
		String sql = null;			 
		ContentValues args = new ContentValues();			
		
		//KSE - Create new entry into database.		
		args.put(COL_NAME, obj.getName());
		database.insert(TABLE_USERS, null, args);

		//KSE - Get last entry from database.
		sql  = "SELECT * FROM " + TABLE_USERS + " WHERE id = last_insert_rowid()";		
		cursor = database.rawQuery(sql, null);		
		if(cursor.moveToFirst())
			obj.setId(cursor.getInt(0));
				
		return obj;	
	}

	@Override
	public void update(User obj) {
		
		String sql = null;
		
		//KSE - Update the attribute object "obj".
		sql = "UPDATE " +  TABLE_USERS + " SET name = " + "\'" + obj.getName() + "\'";		
		
		database.rawQuery(sql, null);
		
		database.close();
	}

	@Override
	public void delete(User obj) {

String sql = null;
		
		//KSE - Delete the attribute object "obj".
		sql = "DELETE FROM " +  TABLE_USERS + " WHERE id = " +  String.valueOf(obj.getId());
		
		database.rawQuery(sql, null);
		
		database.close();
	}
}
